let WebIM = require("./WebIM")["default"];
class IM {
	constructor(arg) {}
	loginImBytoken(username, token) {
		console.log('loginImBytoken---loginImBytoken----loginImBytoken');
		uni.setStorage({
			key: "myUsername",
			data: username.toLowerCase()
		});
		// WebIM.conn.close()
		getApp().globalData.conn.open({
			// apiUrl: WebIM.config.apiURL,
			user: username.toLowerCase(),
			accessToken: token,
			appKey: WebIM.config.appkey,
			success(res) {
				console.log('环信登录成功', res);
			},
			error(err) {
				console.log('环信登录失败', err);
			}
		});
	}
	/**
	 * 获取用户属性
	 * @param {String | Array} users 用户id 
	 */
	fetchUserInfoById(users) {
		return WebIM.conn.fetchUserInfoById(users)
	}
	/**
	 * 设置用户属性
	 * @param {string} options.nickname
	 * @param {string} options.avatarurl
	 * @param {string} options.mail
	 * @param {string} options.phone
	 * @param {string} options.gender
	 * @param {string} options.birth
	 * @param {string} options.sign
	 * @param {string} options.ext
	 */
	updateOwnUserInfo(options) {
		WebIM.conn.updateOwnUserInfo(options).then(res => {
			console.log('updateImUserInfoSucc', res);
		})
	}
	/**
	 * 把消息按用户进行包裹
	 */
	packageMsgStorage(sessionKey, curChatMsg) {
		return new Promise((resolve, reject) => {
			let imUserName = uni.getStorageSync('imUserName')
			if (imUserName) {
				let imMsgList = uni.getStorageSync(imUserName) || {}
				imMsgList[sessionKey] = curChatMsg
				uni.setStorage({
					key: imUserName,
					data: imMsgList,
					success: () => {
						console.log('imUtil.packageMsgStorage', JSON.parse(JSON.stringify(uni
							.getStorageSync(imUserName))));
						resolve()
					}
				})
			}
		})
	}
	/**
	 * 把消息按用户进行解包裹
	 * @params sessionKey 获取聊天记录的key
	 */
	unpackageMsgStorage(sessionKey) {
		console.log('imUtil-unpackageMsgStorage--sessionKey', sessionKey);
		let imUserName = uni.getStorageSync('imUserName')
		// 获取到当前账号的所有聊天记录缓存
		let imMsgList = uni.getStorageSync(imUserName) || {}
		console.log('imUtil-unpackageMsgStorage---imMsgList', imMsgList);
		console.log('imUtil-unpackageMsgStorage---imMsgList[sessionKey]', imMsgList[sessionKey]);
		// 返回当前聊天key对应的聊天记录缓存
		return imMsgList[sessionKey] || []
	}
	/**
	 * 清除环信相关缓存（除聊天记录）
	 */
	clearImStorage() {
		uni.removeStorageSync('imToken')
		uni.removeStorageSync('imUserName')
		uni.removeStorageSync('myUsername')
		WebIM.conn.close()
	}
}

export default new IM()
